#include "ROComponent.h"
#include "QQuickROData.h"
#include "ROHost.h"
#include "RONode.h"

ROComponent::ROComponent(QObject *parent):ROSyncCreation(parent)
{

}

QObject *ROComponent::spawnObject(const QVariantMap &param,const QVariantList& players)
{
    if(role() != Host)
    {
        qDebug()<<__func__<<"创建对象失败，该功能只能在服务端使用";
        return nullptr;
    }
    if(!m_comp) return nullptr;

    auto data = getROObjectData(m_comp);
    if(!data)
    {
        qDebug()<<__func__<<"创建对象失败，组件未注册";
        return nullptr;
    }

    auto r = createObject(m_comp,nullptr,param);
    if(!r)
    {
        return nullptr;
    }

    QStringList playerIds;

    for(auto i : players)
    {
        auto player = i.value<ROPlayer*>();
        playerIds << QString::number(player->playerId());
    }

    r->setParent(this);
    registerObject(r,{playerIds.join(",")});

    return r;
}

QObject *ROComponent::spawnObjectPrivate(const QVariantMap &param)
{
    auto r = createObject(m_comp,nullptr,param);
    if(!r)
    {
        return nullptr;
    }

    r->setParent(this);
    registerObjectIndividual(r);
    return r;
}

QQmlComponent *ROComponent::comp() const
{
    return m_comp;
}

void ROComponent::setComp(QQmlComponent *newComp)
{
    if(role() != None)
    {
        qDebug()<<__func__<<"对象已就绪 不能修改该属性";
        return;
    }
    if (m_comp == newComp)
        return;
    m_comp = newComp;
    emit compChanged();
}

QObject *ROComponent::handleCreation(const QStringList &reason)
{
    if(!m_comp) return nullptr;

    auto data = getROObjectData(m_comp);
    if(!data)
    {
        qDebug()<<__func__<<"创建对象失败，组件未注册";
        return nullptr;
    }

    auto playerId = data->node->playerId();
    auto playerListStr = reason.value(0);
    if(!playerListStr.isEmpty())
    {
        if(!playerListStr.split(",").contains(QString::number(playerId)))//该对象不允许在本端创造
        {
            return nullptr;
        }
    }

    auto r = createObject(m_comp,nullptr,{});
    if(!r)
    {
        return nullptr;
    }

    r->setParent(this);
    return r;
}

